<template>
	<view class="pay-container">
		<!-- 头部导航 -->
		<uv-navbar
			bgColor="#f5f5f5"
			:fixed="true"
			titleStyle="color:#000"
			:placeholder="true"
			@leftClick="$onClickLeft"
			leftIconColor="#000"
			title="支付"></uv-navbar>

		<!-- 交易信息 -->
		<view class="trade-info">
			<view class="remain-time">
				<text v-if="countdown != '订单已超时'">交易剩余时间</text>
				{{ countdown }}
			</view>
			<view class="amountClass">
				<text class="signClass">¥</text>
				<text>{{ amount && amount.toFixed(2) }}</text>
			</view>
		</view>

		<!-- 支付方式区域 -->
		<view class="pay-methods">
			<view class="section-title">支付方式</view>
			<view class="method-group" v-if="otherPayMethods.length">
				<uv-radio-group
					:activeColor="themeColor"
					size="22"
					iconSize="16"
					v-model="payType"
					placement="column"
					iconPlacement="right">
					<uv-radio
						:name="item.payCode"
						:label="item.payName"
						v-for="(item, index) in otherPayMethods"
						:key="index">
						<view class="labelClass">
							<image
								class="method-icon"
								:src="item.imageUrl"
								mode="aspectFit"></image>
							<text class="item-text">
								{{ item.payName }}
								<text v-if="item.payCode == 'yue'">
									（余额￥{{ member.nowMoney || 0 }}）
								</text>
							</text>
						</view>
					</uv-radio>
				</uv-radio-group>
			</view>
		</view>

		<!-- 底部操作栏 -->
		<view class="bottom-bar" v-if="currentOrderInfo.isTimeout != 1">
			<button class="confirm-btn" @click="confirmPay">立即支付</button>
		</view>
	</view>
</template>

<script setup>
	import { ref, onMounted, onUnmounted } from 'vue'
	import { useMainStore } from '@/store/store'
	import { storeToRefs } from 'pinia'
	import { payUnify, orderDetail, AggregateQuery, payList } from '@/api/order'
	import { isWeixin } from '@/utils/util'
	import { onLoad, onShow, onPullDownRefresh, onHide } from '@dcloudio/uni-app'
	const main = useMainStore()
	const { themeColor, member } = storeToRefs(main)
	// 数据定义
	const amount = ref(0) // 订单金额

	// 选中的支付方式
	const payType = ref('weixin')
	// 其他支付方式列表
	const otherPayMethods = ref([
		// {
		// 	payName: '微信支付',
		// 	payCode: 'weixin',
		// 	imageUrl: 'http://121.224.76.39:8002/qingzhen/20250731/酒店-微信支付 (2)_1753958717492.png',
		// },
		// {
		// 	payName: '通联支付',
		// 	payCode: 'tlWxPay',
		// 	imageUrl: 'http://121.224.76.39:8002/qingzhen/20250731/酒店-微信支付 (2)_1753958717492.png',
		// },
		// {
		// 	payName: '建设银行支付',
		// 	payCode: 'digitalRMB',
		// 	imageUrl: 'http://121.224.76.39:8002/qingzhen/20250731/建设银行 (1)_1753958914868.png',
		// },
		// {
		// 	payName: '支付宝支付',
		// 	payCode: 'alipay',
		// 	imageUrl: 'http://121.224.76.39:8002/qingzhen/20250731/支付宝支付 (1)_1753958871067.png',
		// },
		// {
		// 	payName: '云闪付',
		// 	payCode: 'unionPay',
		// 	imageUrl: 'http://121.224.76.39:8002/qingzhen/20250731/云闪付_1753958809667.png',
		// },
		// {
		// 	payName: '余额',
		// 	payCode: 'yue',
		// 	imageUrl: 'http://121.224.76.39:8002/qingzhen/20250731/钱包，余额_1753959592329.png',
		// },
		// {
		// 	payName: '现金',
		// 	payCode: 'cash',
		// 	imageUrl: 'http://121.224.76.39:8002/qingzhen/20250731/现金贷_1753959753384.png',
		// },
	])
	const orderId = ref('')
	// 确认支付事件
	const confirmPay = async () => {
		// main.DEL_COUPON()
		uni.showLoading({
			title: '加载中',
		})
		if (payType.value == 'weixin') {
			// 微信支付
			await weixinPay()
		} else if (payType.value == 'yue') {
			// 余额支付
			await balancePay()
		} else if (payType.value == 'alipay') {
			// 余额支付
			await aliPay()
		} else if (payType.value == 'cash') {
			uni.showToast({
				title: '订单已创建，请到前台结算',
				icon: 'none',
			})
			setTimeout(() => {
				paySuccess()
			}, 500)
		} else if (payType.value == 'tlWxPay') {
			await tonglianPay()
		}
		uni.hideLoading()
		uni.$emit('reloadCurrentListForOrder') // 发送事件
	}
	function compareVersion(version1, version2) {
		const v1 = version1.split('.').map(Number)
		const v2 = version2.split('.').map(Number)

		for (let i = 0; i < v1.length || i < v2.length; i++) {
			const num1 = v1[i] || 0
			const num2 = v2[i] || 0

			if (num1 > num2) {
				return 1
			} else if (num1 < num2) {
				return -1
			}
		}

		return 0
	}
	const tonglianPay = async () => {
		let params = await payUnify({
			uni: orderId.value,
			from: 'routine',
			paytype: 'tlWxPay',
			msg: '商品购买',
		})
		const version = uni.getAppBaseInfo().SDKVersion
		console.log(version, 'version')
		console.log(params, 'params')
		if (compareVersion(version, '2.26.2') >= 0) {
			console.log('进来了')
			// openEmbeddedMiniProgram，需要小程序基础库版本不低于 2.26.2
			uni.openEmbeddedMiniProgram({
				appId: 'wxef277996acc166c3',
				extraData: params.data,
				success(res) {
					uni.setStorageSync('tototo', 1)
				},
			})
		} else {
			uni.navigateToMiniProgram({
				appId: 'wxef277996acc166c3',
				extraData: params.data,
				success(res) {
					uni.setStorageSync('tototo', 1)
				},
			})
		}
	}
	const weixinPay = async () => {
		let from = 'routine'
		// #ifdef H5
		from = 'h5'
		if (isWeixin()) {
			from = 'wechat'
		}
		// #endif
		let data = await payUnify({
			uni: orderId.value,
			from: from,
			paytype: 'weixin',
			msg: '商品购买',
		})
		console.log('param2:', data)
		if (!data) {
			uni.hideLoading()
			return
		}
		if (data.trade_type == 'MWEB') {
			// #ifdef H5
			// 微信外的H5
			console.log('data:', data)
			location.href = data.data
			// #endif
			console.log('data1:', data)
		} else if (data.trade_type == 'JSAPI') {
			console.log('param:', data)

			// #ifdef MP-WEIXIN
			uni.requestPayment({
				provider: 'wxpay',
				timeStamp: data.data.timeStamp,
				nonceStr: data.data.nonceStr,
				package: data.data.package,
				signType: 'MD5',
				paySign: data.data.paySign,
				success: function (res) {
					paySuccess()
				},
				fail: function (err) {
					console.log('fail:' + JSON.stringify(err))
				},
			})
			// #endif
		} else if (data.trade_type == 'W-JSAPI') {
			//公众号支付
		} else if (data.trade_type == 'APP') {
		}
	}

	const aliPay = async () => {
		// #ifdef H5
		if (isWeixin()) {
			uni.showToast({
				title: '请普通浏览器打开进行支付宝支付~',
				icon: 'none',
			})
			return
		}
		let data = await payUnify({
			uni: orderId.value,
			from: 'h5',
			paytype: 'alipay',
		})

		console.log('data:', data.data)
		// 支付宝支付，这里只要提交表单
		let form = data.data
		const div = document.createElement('formdiv')
		div.innerHTML = form
		document.body.appendChild(div)
		//document.forms[0].setAttribute('target', ' self');
		document.forms[0].submit()
		//div.remove();

		// #endif
	}
	const balancePay = async () => {
		let from = 'routine'
		// #ifdef H5
		from = 'h5'
		// #endif
		let pay = await payUnify({
			uni: orderId.value,
			from: from,
			paytype: 'yue',
		})

		uni.hideLoading()
		if (!pay) {
			return
		}

		member.value.money -= amount.value
		main.SET_MEMBER(member.value)
		paySuccess()
	}
	const paySuccess = () => {
		console.log('支付成功')
		if (!currentOptions.value.noSaveOrderId) {
			uni.$emit('openLoading')
		}
		setTimeout(() => {
			uni.navigateBack({
				delta: 2,
			})
			// uni.switchTab({
			// 	url: '/pages/order/order',
			// })
		}, 300)
	}
	// 目标时间：1753962230000
	const countdown = ref('')
	let timer = null

	const updateCountdown = () => {
		const currentTime = Date.now() // 获取当前时间（毫秒）
		const timeElapsed = currentTime - currentOrderInfo.value.createTime // 已过去的时间（毫秒）
		const remainingTime = 15 * 60 * 1000 - timeElapsed // 剩余时间（15分钟 - 已过去的时间）

		if (remainingTime <= 0) {
			countdown.value = '订单已超时' // 如果超过15分钟，显示“超时”
			clearInterval(timer) // 停止倒计时
		} else {
			// 如果剩余时间大于0，计算剩余分钟和秒数
			const minutes = Math.floor(remainingTime / 1000 / 60)
			const seconds = Math.floor((remainingTime / 1000) % 60)
			countdown.value = `${minutes}:${seconds < 10 ? '0' + seconds : seconds}`
		}
	}
	const currentOrderInfo = ref({})
	const detail = async () => {
		let data = await orderDetail(orderId.value)
		if (data) {
			currentOrderInfo.value = data
			updateCountdown() // 初次加载时立即更新倒计时
			timer = setInterval(updateCountdown, 1000) // 每秒更新一次倒计时
			amount.value = Number(data.payPrice)
		}
	}
	const AggregateQueryMethod = async () => {
		console.log('自行轮询', orderId.value, 1111)
		const res = await AggregateQuery({
			uni: orderId.value,
			paytype: 'tlWxPay',
		})
		console.log('data222', res)
		if (res && (!res.trxstatus || res.trxstatus == '2008' || res.trxstatus == '2000')) {
			console.log('又掉')
			setTimeout(AggregateQueryMethod, 500) // 3 秒后再调
		} else {
			console.log('拜拜了您呢')
			paySuccess()
		}
	}
	const getPayList = async () => {
		let data = await payList()
		otherPayMethods.value = data
		payType.value = data[0].payCode
	}
	const currentOptions = ref({})
	onLoad(options => {
		console.log(options, 'options22')
		currentOptions.value = options
		orderId.value = options.id
		if (!currentOptions.value.noSaveOrderId) {
			uni.setStorageSync('currentOrderId', orderId.value)
			uni.removeStorageSync('cart')
			uni.removeStorageSync('deskPeople')
		}
		getPayList()
		detail()
	})
	onShow(() => {
		let options = uni.getEnterOptionsSync()
		let tototo = uni.getStorageSync('tototo')
		if (
			options.scene == '1038' &&
			options.referrerInfo.appId == 'wxef277996acc166c3' &&
			tototo
		) {
			// 代表从收银台小程序返回
			let extraData = options.referrerInfo.extraData
			console.log('返回的參數', extraData)
			if (!extraData) {
				console.log('当前通过物理按键返回，未接收到返参，建议自行查询交易结果')
				AggregateQueryMethod()
				// "当前通过物理按键返回，未接收到返参，建议自行查询交易结果";
			} else {
				if (extraData.code == 'success') {
					// "支付成功";
					paySuccess()
				} else if (extraData.code == 'cancel') {
					// "支付已取消";
					uni.showToast({
						title: '支付已取消！！！',
						icon: 'none',
					})
				} else {
					uni.showToast({
						title: `支付失败：${extraData.errmsg}`,
						icon: 'none',
					})
					// "支付失败：" + extraData.errmsg;
				}
			}
			uni.setStorageSync('tototo', '')
		}
	})
	// 启动倒计时
	onMounted(() => {})
	// 组件销毁时清除定时器
	onUnmounted(() => {
		clearInterval(timer)
	})
</script>

<style scoped lang="scss">
	.pay-container {
		width: 100%;
		height: 100%;
		background-color: #f5f5f5;
	}

	/* 交易信息 */
	.trade-info {
		padding: 40rpx 30rpx;
		text-align: center;
	}
	.remain-time {
		font-size: 26rpx;
		color: #999;
		margin-bottom: 14rpx;
	}
	.amountClass {
		font-size: 50rpx;
		font-weight: bold;
		font-family: OPPOSANS;
		color: $qingzhen-btn-primary-color;
		vertical-align: bottom;
		.signClass {
			margin-right: 4rpx;
			font-size: 34rpx;
		}
	}

	/* 支付方式区域 */
	.pay-methods {
		padding: 0 30rpx;
	}
	.section-title {
		font-size: 30rpx;
		font-weight: bold;
		margin: 30rpx 0 20rpx;
		color: #999;
	}
	.method-group {
		background-color: #fff;
		border: 1px solid #f5f5f5;
		border-radius: 16rpx;

		::v-deep .uv-radio {
			padding: 30rpx;
			border-bottom: 2rpx solid #f5f5f5;
			.uv-radio__label-wrap {
				padding-left: 0 !important;
			}
		}
		.labelClass {
			display: flex;
			align-items: center;
			.method-icon {
				width: 38rpx;
				height: 38rpx;
				margin-right: 16rpx;
			}
			.item-text {
				font-size: 30rpx;
				flex: 1;
			}
		}
	}

	/* 底部操作栏 */
	.bottom-bar {
		position: fixed;
		bottom: 60rpx;
		left: 0;
		width: 100%;
		height: 70rpx;
		padding: 0 50rpx;
	}
	.confirm-btn {
		background-color: $qingzhen-btn-primary-color;
		color: #000;
		font-size: 30rpx;
		padding: 10rpx 20rpx;
		color: #fff;
		border-radius: 200px;
		width: 100%;
	}
</style>
